package renpyas3.view.components 
{
	import fl.transitions.easing.Regular;
	import fl.transitions.easing.Strong;
	import fl.transitions.Tween;
	import fl.transitions.TweenEvent;
	import org.osflash.thunderbolt.Logger;

	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	/**
	 * applies transitions to the given image
	 * dispatches event when is finished
	 */
	public class TransitionEngine extends EventDispatcher
	{
		public static const TRANSITION_FINISHED:String = "transitionFinished";
		private static const TRANSITION_TIME_SECS:Number= 0.35;

		private var _transitionName:String;
		private var _imageToApplyTrans:DisplayObject;
		private var _tween:Tween;
		
		public function TransitionEngine() 
		{
			
		}

		/**
		 * starts fade in or fade out transitions
		 */
		public function startTransition(transitionName:String, imageToApplyTrans:DisplayObject):void
		{
			_transitionName = transitionName;
			_imageToApplyTrans = imageToApplyTrans;

			//Logger.info("TransitionEngine::startTransition  called --_transitionName:", _transitionName, "  --_imageToApplyTrans:",_imageToApplyTrans.name, "  --alpha:",_imageToApplyTrans.alpha);
			
			//finish and stop old transition, if any
			fforwardTransition();
			
			if (imageToApplyTrans.alpha == 1)
			{
				//fade out
				Logger.info("TransitionEngine::startTransition  --fade out _imageToApplyTrans:"+_imageToApplyTrans.name)

				_tween = new Tween(imageToApplyTrans, "alpha", Regular.easeInOut , 1, 0, TRANSITION_TIME_SECS, true);						
			}
			else
			{
				//fade in
				Logger.info("TransitionEngine::startTransition  --fade in _imageToApplyTrans:"+_imageToApplyTrans.name)

				_tween = new Tween(imageToApplyTrans, "alpha", Regular.easeInOut , 0, 1, TRANSITION_TIME_SECS, true);						
			}
			_tween.addEventListener(TweenEvent.MOTION_FINISH, handleTransitionFinished,false,0,true);
		}
		
		
		/**
		 * finish transition immediatelly
		 */
		public function fforwardTransition():void
		{
			Logger.info("TransitionEngine::fforwardTransition --_tween:"+_tween);
			if (_tween != null)
			{
				_tween.removeEventListener(TweenEvent.MOTION_FINISH, handleTransitionFinished);
				
				Logger.info("TransitionEngine::fforwardTransition --_tween.isPlaying:"+_tween.isPlaying);
				if (_tween.isPlaying)
				{
					_tween.stop();
				}
				
				_tween = null;
			}
		}
		
		protected function handleTransitionFinished(e:Event):void
		{
			_tween.removeEventListener(TweenEvent.MOTION_FINISH, handleTransitionFinished);
			Logger.info("TransitionEngine::handleTransitionFinished --_imageToApplyTrans:",_imageToApplyTrans.name)
			dispatchEvent(new Event(TRANSITION_FINISHED));
		}
	}
}